import matplotlib.pyplot as plt
import pandas as pd
import warnings
from sklearn.cluster import KMeans
import numpy as np
warnings.filterwarnings('ignore')
df=pd.read_csv('air_data.csv')

print(df.head())
print(df.info)
print(df.describe())

data=df[df['SUM_YR_1'].notnull()&df['SUM_YR_2'].notnull()]

index1=data['SUM_YR_1']>0
index2=data['SUM_YR_2']>0
index3=(data['SEG_KM_SUM']!=0)&(data['avg_discount']!=0)

dat=data[index1|index2|index3]
print(df.shape)
print(data.shape)
#[ "FFP_DATE" 入会注册时间,
# "LOAD_TIME",上次登陆时间
#  "FLIGHT_COUNT",飞行次数
# "SUM_YR_1",第一年消费总额
# "SUM_YR_2",第二年消费总额
# "SEG_KM_SUM",飞行总里程
# "AVG_INTERVAL" , 平均乘坐飞机的时间间隔（对该乘客而言，正常乘坐飞机的间隔）
# "MAX_INTERVAL", 最大乘坐飞机的时间间隔
# "avg_discount" 平均折扣率
data=data[[ "FFP_DATE", "LOAD_TIME", "FLIGHT_COUNT", "SUM_YR_1", "SUM_YR_2", "SEG_KM_SUM", "AVG_INTERVAL" , "MAX_INTERVAL", "avg_discount"]]

data['FFP_DATE']=pd.to_datetime(data['FFP_DATE'])
data['LOAD_TIME']=pd.to_datetime(data['LOAD_TIME'])

data['入会时间长度']=data['LOAD_TIME']-data['FFP_DATE']
data['每公里票价']=(data["SUM_YR_1"]+data["SUM_YR_2"])/data["SEG_KM_SUM"]
data['时间间隔差值']=data['MAX_INTERVAL']-data['AVG_INTERVAL']

data=data.rename(columns={'FLIGHT_COUNT':'飞行次数',"SEG_KM_SUM":'总里程',"avg_discount":'平均折扣率'})
data=data[['入会时间长度','飞行次数','每公里票价','总里程','时间间隔差值','平均折扣率']]

data['入会时间长度']=data['入会时间长度'].astype('int64')/(24*60*60*10**9)
print(data['入会时间长度'].head())
from sklearn.preprocessing import StandardScaler
ss=StandardScaler()
cn=list(data.columns)
cn.append(cn[0])
data=ss.fit_transform(data)
s=[]
for i in range(4,7):
    model=KMeans(n_clusters=i)
    model.fit(data)
    sse=model.inertia_
    s.append(sse)
    plt.rcParams['font.sans-serif'] = 'SimHei'
    ccl=model.cluster_centers_
    for c in ccl:
        cc=list(c)
        cc.append(cc[0])
        angle=np.linspace(0,2*np.pi,6,endpoint=False)
        angle=list(angle)
        angle.append(angle[0])
        plt.polar(angle,cc)
        plt.xticks(angle,cn)
    plt.show()
plt.plot(range(4,7),s)
plt.show()

#最终选择k=5
model=KMeans(n_clusters=5)
model.fit(data)
labels=model.labels_

s1=pd.Series(labels)
s2=s1.value_counts()
print(s2)

plt.bar(range(0,5),s2)
ticks=['一般保持客户', '易流失客户', '低价值客户', '重点发展客户', '重点保持客户']
plt.xticks(range(0,5),ticks)
plt.show()

plt.pie(s2,labels=ticks,autopct='%2.1f%%')
plt.show()